#!/usr/bin/env python2.5


__author__ = "Fabian Rothfuchs"
__license__ = "GNU General Public License v3"
__version__ = "$Revision: 1.02 $"

import MySQLdb
import os.path
from optparse import OptionParser
from shutil import copyfile


class NFOgen:

    def __init__ (self):
        """constructor"""

        self.writeCount = 0 #counts written files
        self.skipCount = 0 #counts skipped files (always existing)
        self.fileCount = 0 #number of files in the database
        self.backupCount = 0 #number of backupped files
        self.dummyCount = 0 #number pseudo-written of dummy files

        self.readOpts()
        self.getMySQLConfig()
        self.initSQL()

    def __del__(self):
        """destructor"""

        try:
            self.options
        except AttributeError: #-h option diesnt set self.options and exits immediately
            return

        print "Found %s files in database" %(self.fileCount)
        print "Wrote %s files" %(self.writeCount)
        print "Wrote %s dummy files" %(self.dummyCount)
        print "Skipped %s files" %(self.skipCount)

        self.closeSQL()

    def getMySQLConfig(self):
        """gather mysql config by using mythtv config file
        called by: __init__()
        return: None

        """

        mysql_file = '/etc/mythtv/mysql.txt'
        config = {}

        try:
            f = open(mysql_file,'r')
            file = f.read()
            f.close()
        except IOError, e:
            print "Could not open %s ." %(mysql_file,)

        for line in file.split("\n"):
            if line.startswith("#") or len(line) < 1 or not "=" in line:
                continue

            key,val = line.split("=")
            config[key] = val

        self.sql_hostname = config.get('DBHostName','')
        self.sql_username = config.get('DBUserName','')
        self.sql_password = config.get('DBPassword','')
        self.sql_database = config.get('DBName','')

    def readOpts(self):
        """read options given and store them
        called by: __init__()
        return: None
        
        """

        parser = OptionParser()
        parser.add_option("-d", "--dummy", dest="dummy", default=False, action="store_true",
                      help="do not create, just print files and content")
        parser.add_option("-f", "--force", dest="force", default=False, action="store_true",
                      help="force overwriting of existing files")
        parser.add_option("-n", "--no-backup", dest="no_backup", default=False, action="store_true",
                      help="do NOT create .backup files")
        parser.add_option("-q", "--quiet", dest="quiet", default=False, action="store_true",
                      help="don't print status messages")
        parser.add_option("-v", "--verbose", dest="verbose", default=False, action="store_true",
                      help="print verbose messages")
        parser.add_option("-p", "--path", dest="path", default=False, metavar="PATH",
                      help="specify path where to recover NFO files")

        self.options, self.args = parser.parse_args()

    def initSQL(self):
        """initialize MySQL connection
        called by: __init__()
        """

        self.my_conn = MySQLdb.connect(self.sql_hostname, self.sql_username, self.sql_password, self.sql_database)
        self.my_curs = self.my_conn.cursor()

        query = "SELECT title, inetref, filename FROM videometadata"

        self.my_curs.execute(query)
        self.files = self.my_curs.fetchall()

    def closeSQL (self):
        """close MySQL connection
        called by: __del__()
        return: None
        
        """

        self.my_curs.close()
        self.my_conn.close()

    def notify(self, content):
        """print `content` if not quiet mode
        return: None

        content: <str>

        """

        if self.options.quiet:
            return

        print content

    def writeNFO (self, filepath, content):
        """write NFO file to path given in `filepath`
        called by: self.parseDbEntries()
        return: None

        filepath: <str>, i.e. /home/me/a.nfo
        content:  <str>, i.e. blah

        """

        msg = filepath
        if self.options.verbose:
            msg = "%s: \n%s" %(filepath, content)

        if self.options.dummy:
            self.dummyCount += 1
            self.notify("Dummy mode: Would write %s" %(msg,))
            return

        if self.options.path:
            index = filepath.rfind("/")
            folder = filepath[:index]
            filename = filepath[index:]

            if not self.options.path.startswith("/"): #relative paths require `pwd`
                self.options.path = "%s/%s" %(os.getcwd(), self.options.path)
            folder = self.options.path + folder

            if not os.path.exists(folder):
                os.makedirs(folder)

            filepath = folder + filename

        if os.path.exists(filepath): #backup procedure
            if not self.options.force:
                self.writeCount -= 1
                print "File exists: %s - please give -f option to overwrite" %filepath
                return
            else:
                if not self.options.no_backup:
                    self.notify("Backupping file: %s" %filepath)
                    copyfile(filepath, folder + filename + ".backup")

        self.writeCount += 1
        self.notify("Writing NFO file: %s" %filepath)

        f = open(filepath, 'w')
        f.write(content+"\n")
        f.close()

        self.notify("Wrote %s" %(msg,))

    def parseDbEntries (self):
        """parse DB entries received in self.initSQL().
        called by: main method
        return: None

        """
        c = 0
        for entry in self.files:
            title, inetref, filepath = entry
            filepath = "%s.nfo" %filepath[:filepath.rfind(".")]

            if inetref == "00000000" or inetref == "":
                continue

            c+=1
            if inetref.startswith("http://www.thetvdb.com"):
                content = "<thetvdb episodeid='%s'/>" %inetref.split("/")[-2] 
            else:
                content = "<imdb id='tt%s'/>" %inetref
                
            self.writeNFO(filepath, content) 


if __name__ == "__main__":

    n = NFOgen()
    n.parseDbEntries()
